package com.atguigu.ssoserver.controller;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author polaris
 * @date 2021/1/21 4:59 下午
 */
@Controller
public class LoginController {

  @Resource
  StringRedisTemplate stringRedisTemplate;

  @ResponseBody
  @GetMapping("/userInfo")
  public String userInfo(@RequestParam("token") String token) {
    String s = stringRedisTemplate.opsForValue().get(token);
    return s;
  }

  @PostMapping("/doLogin")
  public String doLogin(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        @RequestParam("url") String url, HttpServletResponse response) {
    if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
      //登陆成功，把用户存起来
      String uuid = UUID.randomUUID().toString().replace("-", "");
      stringRedisTemplate.opsForValue().set(uuid, username);
      //保存cookie
      Cookie ssoToken = new Cookie("sso_token", uuid);
      response.addCookie(ssoToken);
      //登陆成功，跳回之前页
      return "redirect:" + url + "?token=" + uuid;
    }
    //失败展示登陆页
    return "login";
  }

  @GetMapping("/login.html")
  public String login(@RequestParam("redirect_url") String url, Model model,
                      @CookieValue(value = "sso_token", required = false) String sso_token) {

    if (!StringUtils.isEmpty(sso_token)) {
      //说明之前有人登陆
      return "redirect:" + url + "?token=" + sso_token;
    }
    model.addAttribute("url", url);
    return "login";
  }
}
